package com.junior.fixclub;

import android.os.Environment;
import android.util.Log;
import com.jaredrummler.android.shell.Shell;
import com.junior.fixclub.party.FixBuild;
import com.junior.fixclub.party.FixDisplay;
import com.junior.fixclub.party.FixPhone;
import com.junior.fixclub.party.FixSystem;
import com.junior.fixclub.party.NativeHandle;
import com.junior.fixclub.util.DeviceUtil;
import com.junior.fixclub.util.FileUtil;

import java.io.File;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class ResolveHook implements IXposedHookLoadPackage {
    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
        //通过目标包名过滤
        if (Entery.hostAppPackages.contains(lpparam.packageName)) {

            ParamMaker.make();
            DeviceUtil.make();
            Log.e("FixClub","启动了article软件9999");

            String libpath = "/data/data/" + lpparam.packageName + "/tmphx/libnativehook.so";
            File libfile = new File(libpath);
            if(libfile.exists()) {
                libfile.delete();
            }
            if(!new File(libpath).exists()) {
                //CommandResult result = Shell.SH.run("cp /sdcard/libnativehook.so /data/local/tmp/|chmod -R 777 /data/local/tmp/libnativehook.so");
                boolean result = FileUtil.copyFileToDir(Environment.getExternalStorageDirectory().getAbsolutePath() + "/fixclub/libnativehook.so", "/data/data/" + lpparam.packageName + "/tmphx/");
                if (result) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("NativeHook", "copy so fail!");
                }
            }
            if(libfile.exists()) {
                if (!FileUtil.getAllSOLoaded()) {
                    System.load(libpath);
                }

                NativeHandle.start();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            NativeHandle.refresh(true);
                            try {
                                Thread.sleep(300);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }

            new FixSystem().handleLoadPackage(lpparam);
            new FixBuild().Fix(lpparam);
            new FixPhone().Fix(lpparam);
            new FixDisplay().Fix(lpparam);
        }
    }

    public static boolean getRoot() {
        if (Shell.SU.isSU("su")) {
            boolean available = Shell.SU.available();
            return available;
        }
        return false;
    }
}

